package com.frame.common.core.security.utils;


import com.frame.common.core.security.entity.SecurityUser;
import com.frame.exception.CustomException;
import com.frame.stant.constans.ResultCode;
import com.frame.stant.utils.SpringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 安全服务工具类
 * 
 * @author ruoyi
 */
public class SecurityUtils {
    /**
     * 获取用户账户
     **/
    public static String getUsername() {
        try {
            return getLoginUser().getUsername();
        } catch (Exception e) {
            throw new CustomException("获取用户账户异常", ResultCode.USER_ACCESS_UNAUTHORIZED.getCode());
        }
    }

    /**
     * 获取用户
     **/
    public static SecurityUser getLoginUser() {
        try {
            return (SecurityUser) getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new CustomException("获取用户信息异常", ResultCode.USER_ACCESS_UNAUTHORIZED.getCode());
        }
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        return getPasswordEncoder().encode(password);
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword 真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        return getPasswordEncoder().matches(rawPassword, encodedPassword);
    }

    /**
     * 是否为管理员
     * 
     * @param userId 用户ID
     * @return 结果
     */
    public static boolean isAdmin(Long userId) {
        return userId != null && 1L == userId;
    }

    /**
     * 因为在配置类中，可能是注入的BCryptPasswordEncoder，也有可能是默认的DelegatingPasswordEncoder
     * @return
     */
    private static PasswordEncoder getPasswordEncoder(){
        PasswordEncoder passwordEncoder = SpringUtils.getBean(BCryptPasswordEncoder.class);
        return passwordEncoder;
    }
}
